package com.liu.frame.http;

import android.util.Log;


import com.liu.frame.utils.LogUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 刘智强 on 2017/2/13.
 * okhttp的设置
 */

public class WeiLiCaiOkHttp {
    private static OkHttpClient mOkHttpClient;

    //设置缓存目录
//    private static File cacheDirectory = new File(MyApplication.getInstance().getApplicationContext().getCacheDir().getAbsolutePath(), "MyCache");
//    private static Cache cache = new Cache(cacheDirectory, 10 * 1024 * 1024);
    //创建 单例模式（OkHttp官方建议如此操作）
//    public static OkHttpClient getInstance() {
//        if (mOkHttpClient == null) {
//            mOkHttpClient = new OkHttpClient.Builder().build();
//        }
//        return mOkHttpClient;
//    }

    /**
     * 获取OkHttpClient对象
     *
     * @return
     */
    public static OkHttpClient getOkHttpClient() {

        if (null == mOkHttpClient) {
            mOkHttpClient = new OkHttpClient.Builder()
//                    .cookieJar(new CookiesManager())
                    //.addInterceptor(new MyIntercepter())
                    //.addNetworkInterceptor(new CookiesInterceptor(MyApplication.getInstance().getApplicationContext()))
                    //设置请求读写的超时时间
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    /**
                     * 请求之前拦截
                     */
                    .addInterceptor(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            int maxAge = 60 * 60; // 有网络时 设置缓存超时时间1个小时
                            int maxStale = 60 * 60 * 24 * 28; // 无网络时，设置超时为4周
                            Request request = chain.request();
                            Log.e("URL", request.url().toString());
//                            Log.e("传递参数", request.headers().toString());
                            Response response = chain.proceed(request);
                            return response;
                        }
                    })
                    .retryOnConnectionFailure(true)//失败后是否重新连接
//                    .cache(cache)
                    .build();
        }
        return mOkHttpClient;
    }

    //Activity页面所有的请求以Activity对象作为tag，可以在onDestory()里面统一取消,this
    public static void cancelTag(Object tag) {
        LogUtils.e("call集合的长度->"+mOkHttpClient.dispatcher().queuedCalls().size());
        for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {

            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }

    }


}
